<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/userStore'
import { useCartStore } from '@/stores/cartStore'
import { createOrderAPI } from '@/apis/order'
import { getUserShopCartAPI, updateProductNumAPI } from '@/apis/shopCart'
import { getOwnAddressAPI, getCartListAddressAPI } from '@/apis/address'

const router = useRouter()
const userStore = useUserStore()
const cartStore = useCartStore()
const cartList = ref([])

const numChange = async (newVal, oldVal, id) => {
    // console.log(`购物车id: ${id} - new: ${newVal} - old: ${oldVal}`)
    const res = await updateProductNumAPI({ id: id, num: newVal })
    if (res.code === 2000) {
        getCartList()
    }
}

const totalPrice = computed(() => cartList.value.reduce((pre, cur) => pre + (cur.price * cur.number), 0).toFixed(2))

const addressObj = ref({})
const getOneAddress = async () => {
    const res = await getCartListAddressAPI()
    if (res.code === 2000) {
        addressObj.value = res.data
        cartStore.address = res.data 
    }
}

const showDialog = ref(false)
const addressList = ref([])
const showAddressWrapper = async () => {
    const res = await getOwnAddressAPI()
    if (res.code === 2000) {
        addressList.value = res.data
        showDialog.value = true
    }
}
// 切换地址
const switchAddress = (i) => {
    addressObj.value = i
    cartStore.address = i
}

const createOrder = async () => {
    if (cartList.value.length !== 0) {
        if (addressObj.flag !== 0) {
            const products = []
            cartList.value.forEach(i => products.push({ productId: i.productId, skuId: i.skuId }))
            const res = await createOrderAPI({
                addrId: addressObj.value.id,
                orderDetailVos: products
            })
            if (res.code === 2000) {
                cartStore.orderIdList = res.data
                ElMessage({ type: 'success', message: '订单已生成，请尽快付款' })
                router.push({ path: '/order' })
            }
        } else {
            ElMessage({ type: 'warning', message: '请选择一个地址' })
        }
    } else {
        ElMessage({ type: 'warning', message: '购物车为空' })
    }
}

const getCartList = async () => {
    const res = await getUserShopCartAPI()
    // console.log(res)
    if (res.code === 2000) {
        cartList.value = res.data
        cartStore.products = res.data
    }
}

onMounted(() => {
    if (!userStore.token) {
        router.replace({ path: '/login' })
        return
    }
    cartStore.clearAll()
    getOneAddress()
    getCartList()
})
</script>

<template>
<div class="xtx-cart-page">
<div class="address-container">
    <div class="empty" v-if="addressObj.flag === 0">你还没有任何地址，快去添加一个吧！</div>
    <div class="address-card" v-else>
        <div class="address-info">
            <div class="info-item">
                <div class="label">收货人：</div>
                <div>{{ addressObj.consignee }}</div>
            </div>
            <div class="info-item">
                <div class="label">收货地址：</div>
                <div>{{ addressObj.detail }}</div>
            </div>
            <div class="info-item">
                <div class="label">收货手机号：</div>
                <div>{{ addressObj.phone }}</div>
            </div>
        </div>
    </div>
    <div class="operation">
        <RouterLink to="/userCenter/address" v-if="addressObj.flag === 0">添加地址</RouterLink>
        <a href="#" @click="showAddressWrapper" v-else>切换地址</a>
        
    </div>
</div>
<div>
<div class="cart">
    <table>
        <thead><tr>
            <th width="120"><el-checkbox/></th>
            <th width="400">商品信息</th>
            <th width="220">单价</th>
            <th width="180">数量</th>
            <th width="180">小计</th>
            <th width="140">操作</th>
        </tr></thead>

        <!-- 商品列表 -->
        <tbody>
            <tr v-for="i in cartList" :key="i.id">
                <td><el-checkbox /></td>
                <td>
                    <div class="goods">
                        <RouterLink :to="`/productDetail/${i.id}`"><img :src="i.image" alt="" /></RouterLink>
                        <div><p class="name ellipsis">{{ i.productName }} {{ i.productSku }}</p></div>
                    </div>
                </td>
                <td class="tc">
                    <p>&yen;{{ i.price }}</p>
                </td>
                <td class="tc">
                    <el-input-number 
                    v-model="i.number" 
                    :min="1" 
                    :value-on-clear="1"
                    @change="(newVal, oldVal) => numChange(newVal, oldVal, i.id)" />
                </td>
                <td class="tc">
                    <p class="f16 red">&yen;{{ (i.price * i.number).toFixed(2) }}</p>
                </td>
                <td class="tc">
                    <p>
                        <el-popconfirm title="确认删除吗?" confirm-button-text="确认" cancel-button-text="取消" @confirm="delCart(i)">
                            <template #reference>
                                <a href="javascript:;">删除</a>
                            </template>
                        </el-popconfirm>
                    </p>
                </td>
            </tr>
            <tr v-if="cartList.length === 0">
                <td colspan="6"><div class="cart-none">
                    <el-empty description="购物车列表为空">
                        <el-button type="primary" @click="this.$router.push({ path: '/product' })">随便逛逛</el-button>
                    </el-empty>
                </div></td>
            </tr>
        </tbody>
    </table>

<el-dialog title="切换收货地址" v-model="showDialog" width="30%" center>
    <div class="addressWrapper">
        <div class="text item" 
            v-for="i in addressList"
            :key="i.id"
            :class="{ active: addressObj.id === i.id }"
            @click="switchAddress(i)"
            >
            <ul>
            <li><span>收货人：{{ i.consignee }}</span></li>
            <li><span>联系方式：{{ i.phone }}</span></li>
            <li><span>收货地址：{{ i.detail }}</span></li>
            </ul>
        </div>
    </div>
    <template #footer>
        <span class="dialog-footer">
            <el-button @click="showDialog = false">取消</el-button>
            <el-button type="primary" @click="showDialog = false">确定</el-button>
        </span>
    </template>
</el-dialog>
</div>

<!-- 操作栏 -->
<div class="action">
    <!-- <div class="batch"></div> -->
    <div class="batch">共 {{ cartList.length }} 件商品，商品合计：<span class="red">¥ {{ totalPrice }} </span></div>
    <div class="total"><el-button size="large" type="primary" @click="createOrder">下单结算</el-button></div>
</div>
</div>
</div>
</template>

<style scoped lang="scss">
.addressWrapper {
  max-height: 500px;
  overflow-y: auto;
}

.text {
  flex: 1;
  min-height: 90px;
  display: flex;
  align-items: center;

  &.item {
    border: 1px solid #f5f5f5;
    margin-bottom: 10px;
    cursor: pointer;

    &.active,
    &:hover {
      border-color: $xtxColor;
      background: lighten($xtxColor, 50%);
    }

    >ul {
      padding: 10px;
      font-size: 14px;
      line-height: 30px;
    }
  }
}

.address-container {
    width: 1280px;
    background-color: #fff;
    margin-bottom: 20px; 
    padding: 20px;
}

.empty {
    color: #525252;
    margin-bottom: 20px;
}

.address-card {
    position: relative;
    display: flex;
    justify-content: space-between;
    width: 100%;
    padding: 15px;
    border-radius: 4px;
    border: 1px dashed #a6a6a6;
    color: #525252;
    font-size: 14px;
    margin-bottom: 20px;

    .info-item {
        display: flex;
        margin-bottom: 15px;

        &:last-child {
            margin-bottom: 0;
        }
    }
}

.operation {
    a {
        width: 90px;
        height: 35px;
        line-height: 35px;
        border-radius: 4px;
        display: block;
        font-size: 14px;
        color: #fff;
        background-color: #39bf3e;
        text-align: center;
    }
}

.xtx-cart-page {
    width: 1280px;
    margin: 20px auto;

    .cart {
    background: #fff;
    color: #666;

    table {
        border-spacing: 0;
        border-collapse: collapse;
        line-height: 24px;

        th,
        td {
        padding: 10px;
        border-bottom: 1px solid #f5f5f5;

        &:first-child {
            text-align: left;
            padding-left: 30px;
            color: #999;
        }
        }

        th {
        font-size: 16px;
        font-weight: normal;
        line-height: 50px;
        }
    }
    }

    .cart-none {
    text-align: center;
    padding: 120px 0;
    background: #fff;

    p {
        color: #999;
        padding: 20px 0;
    }
    }

    .tc {
    text-align: center;

    a {
        color: $xtxColor;
    }

    .xtx-numbox {
        margin: 0 auto;
        width: 120px;
    }
    }

    .red {
    color: $priceColor;
    }

    .green {
    color: $xtxColor;
    }

    .f16 {
    font-size: 16px;
    }

    .goods {
        display: flex;
        align-items: center;

        img {
            width: 100px;
            height: 100px;
        }

        >div {
            width: 280px;
            font-size: 16px;
            padding-left: 20px;

            .attr {
                font-size: 14px;
                color: #999;
            }
        }
    }

    .action {
    display: flex;
    background: #fff;
    margin-top: 20px;
    height: 80px;
    align-items: center;
    font-size: 16px;
    justify-content: space-between;
    padding: 0 30px;

    .xtx-checkbox {
        color: #999;
    }

    .batch {
        a {
        margin-left: 20px;
        }
    }

    .red {
        font-size: 18px;
        margin-right: 20px;
        font-weight: bold;
    }
    }

  .tit {
    color: #666;
    font-size: 16px;
    font-weight: normal;
    line-height: 50px;
  }
}
</style>